package checkImg

import (
	"context"
	"project/pkg/dao/redis"
	"strconv"
	"time"
)

const CAPTCHA = "captcha:"

type RedisStore struct {
	c redis.Redis
}

func NewRedisStore(r redis.Redis) RedisStore {
	return RedisStore{c: r}
}
func (r RedisStore) Set(id string, value string) (err error) {
	v, _ := strconv.Atoi(value)
	println(CAPTCHA+id, v)
	//设置验证码2分钟过期
	_, err = r.c.Client.Set(context.Background(), CAPTCHA+id, v, 2*time.Minute).Result()

	return err
}

func (r RedisStore) Get(id string, clear bool) string {
	key := CAPTCHA + id
	re, err := r.c.Client.Get(context.Background(), key).Result()
	println(key + "---" + re)
	if err != nil {
		return ""
	}
	if clear {
		r.c.Client.Del(context.Background(), key)
	}

	return re
}

func (r RedisStore) Verify(id, answer string, clear bool) bool {
	v := r.Get(id, clear)
	return v == answer
}
